package com.fwj.auth.strategy.impl;

import com.alibaba.fastjson.JSONObject;
import com.fwj.auth.api.user.UserService;
import com.fwj.auth.entity.user.UserExtendAccount;
import com.fwj.core.common.common.MailUtil;
import com.fwj.core.common.common.RedisUtil;
import com.fwj.core.common.config.SpringContextHolder;
import com.fwj.core.common.constant.CoreConstant;
import com.fwj.core.common.execption.CommonException;
import com.fwj.core.common.model.Mail;
import com.fwj.core.common.model.ResponseEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author: fwj
 * @Data: 2022/5/4 6:42
 * @Version 1.0
 * @Description:
 */


public enum RegisterStrategyImpl {

    PHONE{

        @Override
        public void exec(JSONObject jsonObject){

        }
    },

    /**
     * 邮箱注册
     * */
    EMAIL{
        private UserService userService = SpringContextHolder.getBean(UserService.class);
        @Override
        public void exec(JSONObject jsonObject){
            try {
                Mail mail = JSONObject.parseObject(jsonObject.toJSONString(),Mail.class);
                //检测用户是否存在
                checkUserExists(mail);
                //生成验证码
                String code = String.valueOf(ThreadLocalRandom.current().nextInt(100000,1000000));
                //初始化邮件格式
                buildRegisterMail(mail,code);
                //存储验证码到Redis
                RedisUtil.setTimeOut(CoreConstant.REGISTER + mail.getTo()[0],code,60 * 10);
                //发送邮件
                MailUtil.sendMail(mail);
            } catch (CommonException e){
                LOGGER.error(e.toString());
              throw e;
            } catch (Exception e) {
                LOGGER.error(e.toString());
                throw new CommonException(ResponseEnum.SERVER_ERROR);
            }
        }

        private void checkUserExists(Mail mail) {
            UserExtendAccount userExtendAccount = new UserExtendAccount();
            userExtendAccount.setValue(mail.getTo()[0]);
            if (userService.checkUserExists(userExtendAccount)){
                throw new CommonException(ResponseEnum.USER_EXISTS);
            }
        }

        private Mail buildRegisterMail(Mail mail, String code){
            mail.setSubject("彝族博物馆邮箱注册验证");
            mail.setText("<p> 您的邮箱注册验证码为: <br/>" + code + "<br/> 验证码10分钟内有效 </p>");
            return mail;
        }
    },

    WECHAT{
        @Override
        public void exec(JSONObject jsonObject){

        }

    },

    QQ{
        @Override
        public void exec(JSONObject jsonObject){

        }
    },

    MICRO_BLOG{
        @Override
        public void exec(JSONObject jsonObject){

        }
    },
    ;
    //添加日志工厂
    private static final Logger LOGGER = LoggerFactory.getLogger(RegisterStrategyImpl.class);

    //定义抽象方法，执行更新
    public abstract void exec(JSONObject jsonObject);
}
